package com.zx.sdk.league.member;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.junion.JgAds;
import com.junion.ad.BidLossNotice;
import com.junion.ad.RewardAd;
import com.junion.ad.SplashAd;
import com.junion.ad.base.BaseAdInfo;
import com.junion.ad.bean.RewardAdInfo;
import com.junion.ad.bean.SplashAdInfo;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.RewardAdListener;
import com.junion.ad.listener.SplashAdListener;
import com.junion.biz.bean.DownloadTipType;
import com.junion.config.JUnionCustomController;
import com.junion.config.JUnionInitConfig;
import com.junion.config.JUnionLocationProvider;
import com.zx.sdk.BuildConfig;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.listener.BaseZxRewardListener;
import com.zx.sdk.listener.BaseZxSplashListener;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.model.ReadyAdPosition;
import com.zx.sdk.model.ZxError;
import com.zx.sdk.util.LogHelper;
import com.zx.sdk.util.RunnableHelper;

import java.util.Collections;

import cn.jiguang.jgssp.ADJgSdk;

public class JiGuangBid extends BaseLeagueMember<SplashAdInfo, RewardAdInfo, Object, Object, Object> {
    @Override
    public String getName() {
        return "jgbid";
    }

    @Override
    protected void onInit(Context context, String appId, boolean initialized) {
        RunnableHelper.runOnUIThread(() -> {// 必须在主线程中进行
            // 初始化JgAds广告SDK
            JgAds.getInstance().init(context, new JUnionInitConfig.Builder()
                    // 设置APPID，必须的
                    .appId(appId)
                    // 是否开启Debug，开启会有详细的日志信息打印
                    // 注意上线后请置为false
                    .debug(BuildConfig.DEBUG)
                    .setCustomController(new JUnionCustomController() {
                        @Override
                        public String getDevImei() {
                            return super.getDevImei();
                        }

                        @Override
                        public String getAndroidId() {
                            return super.getAndroidId();
                        }

                        @Override
                        public JUnionLocationProvider getLocation() {
                            return super.getLocation();
                        }

                        @Override
                        public String getMacAddress() {
                            return super.getMacAddress();
                        }

                        @Override
                        public String getDevOaid() {
                             return ZxSDK.oaid;
                        }

                        @Override
                        public String getDevVaid() {
                            return ZxSDK.vaid;
                        }
                    })
                    //【慎改】是否同意隐私政策，将禁用一切设备信息读起严重影响收益
                    .agreePrivacyStrategy(true)
                    .isCanUseLocation(true)// 是否可获取定位数据
                    .isCanUsePhoneState(true)// 是否可获取设备信息
                    .build());
        });
    }

    @Override
    protected void onLoadSplash(AdInfo adInfo, ViewGroup container, String mode, String type, BaseZxSplashListener listener) {
        RunnableHelper.postDelay(500, () -> {
            // 创建开屏广告实例，第一个参数可以是Activity或Fragment，第二个参数是广告容器，第二个参数是自定义跳过按钮
            SplashAd splashAd = new SplashAd(container.getContext());
            // 设置倒计时跳过时长[3000ms~5000ms]
            splashAd.setCountDownTime(5000);
            splashAd.setListener(new SplashAdListener() {
                @Override
                public void onAdTick(long millisUntilFinished) {
                    listener.onADTick(JiGuangBid.this, millisUntilFinished, adInfo);
                }

                @Override
                public void onAdReceive(SplashAdInfo splashAdInfo) {
                    saveSplash(adInfo.getMapPid(), splashAdInfo, container);
                    if (ZxSDK.FETCH_AND_SHOW.equals(mode)) {
                        if (!showSplash(adInfo, container, listener)) {
                            listener.onNoAD(JiGuangBid.this, new ZxError("-1", "广告显示失败"), adInfo);
                            return;
                        }
                    }
                    listener.onADLoaded(JiGuangBid.this, 0, adInfo);
                }

                @Override
                public void onAdExpose(SplashAdInfo splashAdInfo) {
                    listener.onADExposure(JiGuangBid.this, adInfo);
                }

                @Override
                public void onAdClick(SplashAdInfo splashAdInfo) {
                    listener.onADClicked(JiGuangBid.this, adInfo);
                }

                @Override
                public void onAdSkip(SplashAdInfo adInfo) {

                }

                @Override
                public void onAdClose(SplashAdInfo splashAdInfo) {
                    listener.onADDismissed(JiGuangBid.this, adInfo);
                }

                @Override
                public void onAdFailed(JUnionError error) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            listener.onPreLoadNoAD(JiGuangBid.this, new ZxError(String.valueOf(error.getCode()), error.getError()), adInfo);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            listener.onNoAD(JiGuangBid.this, new ZxError(String.valueOf(error.getCode()), error.getError()), adInfo);
                            break;
                    }
                }
            });
            // 加载广告，第一个参数为广告位id
            splashAd.loadAd(adInfo.getMapPid());
        });
    }

    @Override
    public boolean onShowSplash(AdInfo adInfo, ViewGroup container, @Nullable SplashAdInfo splashAdInfo, BaseZxSplashListener listener) {
        if (splashAdInfo == null) return false;
        // 在此回调中展示广告
        // 获取开屏广告视图
        View view = splashAdInfo.getSplashAdView();
        container.addView(view);
        // 渲染开屏广告
        splashAdInfo.render();
        return true;
    }

    @Override
    public void onLoadReward(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        RunnableHelper.postDelay(100, () -> {
            // 创建横幅广告实例，第一个参数可以是Activity或Fragment
            RewardAd rewardAd = new RewardAd(context);
            rewardAd.setListener(new RewardAdListener() {
                @Override
                public void onAdReceive(RewardAdInfo rewardAdInfo) {
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            saveReward(adInfo.getMapPid(), rewardAdInfo);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            rewardAdInfo.showRewardAd(context);
                            break;
                    }
                    listener.onADLoad(JiGuangBid.this, adInfo);
                }

                @Override
                public void onAdReward(RewardAdInfo rewardAdInfo) {
                    listener.onReward(JiGuangBid.this, Collections.emptyMap(), adInfo);
                }

                @Override
                public void onAdExpose(RewardAdInfo rewardAdInfo) {
                    listener.onADExpose(JiGuangBid.this, adInfo);
                }

                @Override
                public void onAdClick(RewardAdInfo rewardAdInfo) {
                    listener.onADClick(JiGuangBid.this, adInfo);
                }

                @Override
                public void onAdClose(RewardAdInfo rewardAdInfo) {
                    listener.onADClose(JiGuangBid.this, adInfo);
                }

                @Override
                public void onVideoCompleted(RewardAdInfo rewardAdInfo) {
                    listener.onVideoComplete(JiGuangBid.this, adInfo);
                }

                @Override
                public void onVideoSkip(RewardAdInfo rewardAdInfo) {
                    listener.onAdSkip(JiGuangBid.this, 0f, adInfo);
                }

                @Override
                public void onVideoError(RewardAdInfo rewardAdInfo, String msg) {
                    listener.onVideoPlayError(JiGuangBid.this, new ZxError("-1", msg), adInfo);
                }

                @Override
                public void onAdFailed(JUnionError adJgError) {
                    int code = -1;
                    String errorMsg = "加载失败";
                    if (adJgError != null) {
                        code = adJgError.getCode();
                        errorMsg = adJgError.getError();
                    }
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            listener.onPreLoadADError(JiGuangBid.this, new ZxError(String.valueOf(code), errorMsg), adInfo);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            listener.onNoAD(JiGuangBid.this, new ZxError(String.valueOf(code), errorMsg), adInfo);
                            break;
                    }
                }
            });
            // 加载广告，第一个参数为广告位id
            rewardAd.loadAd(adInfo.getMapPid());
        });
    }

    @Override
    public boolean onShowReward(Activity context, AdInfo adInfo, @Nullable RewardAdInfo reward, BaseZxRewardListener listener) {
        if (reward == null) return false;
        reward.showRewardAd(context);
        return true;
    }

    @Override
    public void onLoadInterstitial(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {

    }

    @Override
    public boolean onShowInterstitial(Activity context, AdInfo adInfo, @Nullable Object interstitial, BaseZxRewardListener listener) {
        return false;
    }

    @Override
    public boolean isPreResReady(String type, String pid) {
        BaseAdInfo baseAdInfo = getFilledRewardByPid(pid);
        if (baseAdInfo != null) {
            try {
                return !baseAdInfo.hasShow();
            } catch (Exception e) {
                return false;
            }
        }
        return super.isPreResReady(type, pid);
    }

    @Override
    public void clearFilledBiddingAd(String type, String pid) {
        super.clearFilledBiddingAd(type, pid);
        if (ZxSDK.REWARD.equals(type)) {
            RewardAdInfo rewardAdInfo = rewardMap.remove(pid);
            if (rewardAdInfo != null) {
                rewardAdInfo.release();
            }
        } else if (ZxSDK.SPLASH.equals(type)) {
            SplashAdInfo splashAdInfo = splashMap.remove(pid);
            if (splashAdInfo != null) {
                splashAdInfo.release();
            }
        }
    }

    @Override
    public int getCpmByPid(String type, String pid) {
        int cpm = super.getCpmByPid(type, pid);
        try {
            switch (type) {
                case ZxSDK.SPLASH:
                    if (splashMap.containsKey(pid)) {
                        cpm = splashMap.get(pid).getBidPrice();
                    }
                case ZxSDK.REWARD:
                    if (rewardMap.containsKey(pid)) {
                        cpm = rewardMap.get(pid).getBidPrice();
                    }
            }
        } catch (Exception exception) {
            LogHelper.d("JIGUANGBID getCpmByPid exception " + exception.getMessage());
        }
        cpmCache.put(type + pid, cpm);
        return cpm;
    }

    @Override
    public void notifyBiddingWin(String type, String mapPid, @Nullable ReadyAdPosition loser) throws Exception {
        if (ZxSDK.SPLASH.equals(type)) {
            SplashAdInfo splashAdInfo = splashMap.get(mapPid);
            if (splashAdInfo != null) {
                int cpm = splashAdInfo.getBidFloor();
                if (loser != null) {
                    cpm = loser.getCpm();
                }
                splashAdInfo.sendWinNotice(cpm);
            }
        } else if (ZxSDK.REWARD.equals(type)) {
            RewardAdInfo rewardAdInfo = rewardMap.get(mapPid);
            if (rewardAdInfo != null) {
                int cpm = rewardAdInfo.getBidFloor();
                if (loser != null) {
                    cpm = loser.getCpm();
                }
                rewardAdInfo.sendWinNotice(cpm);
            }
        }
        LogHelper.d(getName(), "notifyBiddingWin", mapPid, "selfPrice =" + getCpmByPid(type, mapPid), "LoserPrice = " + (loser != null ? loser.getCpm() : 0));
    }

    @Override
    public void notifyBiddingLose(String type, String mapPid, ReadyAdPosition winner, ZxSDK.LoseReason reason) throws Exception {
        if (ZxSDK.SPLASH.equals(type)) {
            SplashAdInfo splashAdInfo = splashMap.get(mapPid);
            if (splashAdInfo != null) {
                splashAdInfo.sendLossNotice(winner.getCpm(), BidLossNotice.LOW_PRICE);
            }
        } else if (ZxSDK.REWARD.equals(type)) {
            RewardAdInfo rewardAdInfo = rewardMap.get(mapPid);
            if (rewardAdInfo != null) {
                rewardAdInfo.sendLossNotice(winner.getCpm(), BidLossNotice.LOW_PRICE);
            }
        }
        LogHelper.d(getName(), "notifyBiddingLose", mapPid, "selfPrice =" + getCpmByPid(type, mapPid), "WinnerPrice = " + winner.getCpm());
    }
}
